<?php

namespace App\Http\Controllers\Service;

use App\Exceptions\GeneralException;
use App\Http\Controllers\Controller;
use App\Models\AdminUser as Admin;
use App\Repositories\UserLogRepository;
use App\Repositories\AdminUserRepository;
use App\Http\Requests\Station\Admin\ShowRequest;
use App\Http\Requests\Station\Admin\QueryResource;
use App\Http\Requests\Station\Admin\AdminCreate;
use App\Http\Requests\Station\Admin\AdminUpdate;
use App\Http\Requests\Station\Admin\AdminDestroy;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class AdminController extends Controller
{
    protected $adminRepository;
    protected $userLogRepository;

    /**
     * AdminController constructor.
     * @param AdminUserRepository $adminRepository
     * @param UserLogRepository $userLogRepository
     */
    public function __construct(
        AdminUserRepository $adminRepository,
        UserLogRepository $userLogRepository
    )
    {
        $this->adminRepository = $adminRepository;
        $this->userLogRepository = $userLogRepository;
    }

    /**
     * 获取管理员用户资源列表
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param QueryResource $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(QueryResource $request)
    {
        $limit = $request->get('paginate', 15);
        $name = $request->get('name', false);
        $created_at = $request->get('created_at', false);
        if ($name === null) {
            $name = false;
        }
        if ($created_at === null) {
            $created_at = false;
        }
        $admins = Auth::guard('station')->user();
        $service_id = $admins->service_id;
        $admins = $this->adminRepository->getAdmins($name, $created_at, $limit, $service_id);
        return success($admins);
    }

    /**
     * 根据账户Id 获取账户详情资源
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param ShowRequest $request
     * @param $admin
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function show(ShowRequest $request, $admin)
    {
        $limit = $request->get('paginate', 15);
        if (!is_numeric($admin)) {
            return failed('请上传正确的账户id', 422);
        }
        $res = $this->adminRepository->getAdminsDetails($admin, $limit);
        if ($res) {
            return success($res);
        } else {
            return failed('该账户不存在！');
        }
    }

    /**
     * 新建账户资源
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param AdminCreate $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function store(AdminCreate $request)
    {
        $permissions = $request->get('permission', []);
        $attributes = $request->only([
            'name',
            'phone',
            'password',
            'role_name',
        ]);
        if (!is_array($permissions) && count($permissions) == 0) {
            return failed('没有上传权限', 422);
        }
        $admins = Auth::guard('station')->user();
        $service_id = $admins->service_id;
        $attributes['service_id'] = $service_id;
        DB::beginTransaction();
        try {
            $admins = Admin::create($attributes);
            if (is_array($permissions) && count($permissions) > 0) {
                $permission_attribute = [];
                foreach ($permissions as $list) {
                    if (is_array($list['list']) && count($list['list']) > 0) {
                        foreach ($list['list'] as $permission_id) {
                            $permission_attribute[] = [
                                'admin_id' => $admins->id,
                                'privilege_id' => (int)$permission_id,
                                'created_at' => Carbon::now(),
                                'updated_at' => Carbon::now(),
                            ];
                        }
                    }
                }
                if (is_array($permission_attribute) && count($permission_attribute) > 0) {
                    DB::table('station_privilege')->insert($permission_attribute);
                } else {
                    throw new GeneralException('没有上传权限', 422);
                }
            } else {
                throw new GeneralException('没有上传权限', 422);
            }
            //创建权限表
            DB::commit();
        } catch (\Illuminate\Database\QueryException $ex) {
            DB::rollback();
            throw new GeneralException('未知错误', 500);
        }
        //记录日志
        $admin = Auth::guard('station')->user();
        $uid = $admin->id;
        $service_id = 0;
        $name = $admin->name;
        $operation = '创建了账户[' . $admins->phone . ']';
        $history = $actuality = null;
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 3;
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return stored($admins);
    }

    /**
     * 更新用户信息
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param AdminUpdate $request
     * @param Admin $admin
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function update(AdminUpdate $request, Admin $admin)
    {
        $permissions = $request->get('permission', []);
        //店长不允许修改手机号
        if ($admin->is_owner) {
            $adminsAttr = array_filter($request->only([
                'name',
                'password',
                'role_name'
            ]), function ($value) {
                if ($value === null || $value === '') {
                    return false;
                } else {
                    return true;
                }
            });
        } else {
            $adminsAttr = array_filter($request->only([
                'name',
                'phone',
                'password',
                'role_name'
            ]), function ($value) {
                if ($value === null || $value === '') {
                    return false;
                } else {
                    return true;
                }
            });
        }
        if (!is_array($permissions) && count($permissions) == 0) {
            return failed('没有上传权限', 422);
        }
        DB::beginTransaction();
        try {
            $admin->update($adminsAttr);
            //更新权限表
            if (is_array($permissions) && count($permissions) > 0) {
                $permission_attribute = [];
                foreach ($permissions as $list) {
                    if (is_array($list['list']) && count(['list']) > 0) {
                        foreach ($list['list'] as $permission_id) {
                            $permission_attribute[] = [
                                'admin_id' => $admin->id,
                                'privilege_id' => (int)$permission_id,
                                'created_at' => Carbon::now(),
                                'updated_at' => Carbon::now(),
                            ];
                        }
                    }
                }
                if (is_array($permission_attribute) && count($permission_attribute) > 0) {
                    DB::table('station_privilege')
                        ->where('admin_id', '=', $admin->id)
                        ->delete();
                    DB::table('station_privilege')
                        ->insert($permission_attribute);
                } else {
                    throw new GeneralException('没有上传权限', 422);
                }
            } else {
                throw new GeneralException('没有上传权限', 422);
            }
            DB::commit();
        } catch (\Illuminate\Database\QueryException $ex) {
            DB::rollback();
            throw new GeneralException('未知错误', 500);
        }
        //记录日志
        $admins = Auth::guard('station')->user();
        $uid = $admins->id;
        $service_id = $admins->service_id;
        $name = $admins->name;
        $operation = '更新了账户[' . $admin->phone . ']资料';
        $history = json_encode($admin);
        $actuality = json_encode($adminsAttr, true);
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 3;
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        //添加用户权限
        $admin->permission = $this->adminRepository->getPermissionsById($admin->id);
        return updated($admin);
    }

    /**
     * 删除 用户 资源
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param AdminDestroy $request
     * @param Admin $admin
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function destroy(AdminDestroy $request, Admin $admin)
    {
        $admins = Auth::guard('station')->user();
        $uid = $admins->id;
        $service_id = $admins->service_id;
        $name = $admins->name;
        if ($admin->id == $admins->id) {
            return failed('不能删除自己的账号', 403);
        }
        $admin_phone = $admin->phone;
        DB::beginTransaction();
        try {
            $admin->privileges()->detach();
            $admin->delete();
            DB::commit();
        } catch (\Illuminate\Database\QueryException $ex) {
            DB::rollback();
            throw new GeneralException('未知错误', 500);
        }
        //记录日志
        $operation = '删除了账户[' . $admin_phone . ']';
        $history = $actuality = null;
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 3;
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return deleted();
    }

    /**
     * 获取所有权限列表
     *
     * Date: 2018/06/09
     * @author Tenny
     * @param QueryResource $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function permission(QueryResource $request)
    {
        $permissions = $this->adminRepository->getPermissions();
        if ($permissions) {
            return success($permissions);
        } else {
            return failed('获取权限失败！');
        }
    }

    /**
     * 检测手机号码是否存在
     *
     * Date: 2018/06/10
     * @author Tenny
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function existence(Request $request)
    {
        $this->validate($request, [
            'phone' => ['required', 'regex:/^(1[3456789])\d{9}$/', 'unique:admin,phone']
        ], [
            'phone.required' => '请输入手机号码',
            'phone.regex' => '您输入的手机号码有误',
            'phone.unique' => '您输入的手机号码已存在'
        ]);
        return message('可以注册');
    }
}
